const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    mode: 'production',
    entry: {
        config: './js/config.prod.js',
        login: './js/login.js',
        list: './js/list.js',
        upload: './js/upload.js',
        users: './js/users.js',
        styles: './css/styles.css'
    },
    output: {
        filename: 'js/[name].[contenthash].js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: require.resolve('babel-loader'),
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new MiniCssExtractPlugin({
            filename: 'css/[name].[contenthash].css'
        }),
        new HtmlWebpackPlugin({
            template: './html/login.html',
            filename: 'login.html',
            chunks: ['config', 'login', 'styles']
        }),
        new HtmlWebpackPlugin({
            template: './html/index.html',
            filename: 'index.html',
            chunks: ['config', 'list', 'styles']
        }),
        new HtmlWebpackPlugin({
            template: './html/upload.html',
            filename: 'upload.html',
            chunks: ['config', 'upload', 'styles']
        }),
        new HtmlWebpackPlugin({
            template: './html/users.html',
            filename: 'users.html',
            chunks: ['config', 'users', 'styles']
        }),
        new CopyPlugin({
            patterns: [
                { 
                    from: 'upload', 
                    to: 'upload',
                    noErrorOnMissing: true
                },
                { from: 'software_db.json', to: 'software_db.json' },
                { from: 'users_db.json', to: 'users_db.json' }
            ]
        })
    ],
    optimization: {
        splitChunks: {
            chunks: 'all',
            name: 'common'
        }
    }
}; 